﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using VehicleManagement.Models;
using VehicleManagement.Codes;
using VehicleManagement.ControllersServices;
using System.IO;

namespace VehicleManagement.Controllers
{
    //[CustomerAuthorize(Roles = "管理员,负责人")]
    public class DriverManagerController : Controller
    {
        const int PAGE_MAX = 8;
        //
        // GET: /DriverManager/

        public ViewResult Index()
        {
            IList<DriverManager> lstModel;
            string name = Request.Params["Name"];
            string telephone = Request.Params["Telephone"];
            string sex = Request.Params["Sex"];
            string nameForSearch = "%%";
            string telephoneForSearch = "%%";
            string sexForSearch = "%%";
            ApplicantService applicantService = new ApplicantService();

            if (!string.IsNullOrEmpty(name) && name != "姓名")
                nameForSearch = string.Format("%{0}%", name);
            if (!string.IsNullOrEmpty(telephone) && telephone != "电话")
                telephoneForSearch = string.Format("%{0}%", telephone);
            if (!string.IsNullOrEmpty(sex) && sex != "性别")
                sexForSearch = string.Format("%{0}%", sex);
            DriverManagerService dms = new DriverManagerService();
            lstModel = dms.SearchAllDriverManagers(nameForSearch, telephoneForSearch, sexForSearch, (String)Session["CompanyName"]);

            int totalItems = lstModel.Count;

            if (!string.IsNullOrWhiteSpace(Request.Params["Page"]))
            {
                int page = int.Parse(Request.Params["Page"]);
                lstModel = dms.SearchAllDriverManagers(nameForSearch, telephoneForSearch,
                    sexForSearch, (page - 1) * PAGE_MAX, PAGE_MAX, (String)Session["CompanyName"]);
            }
            else
            {
                lstModel = dms.SearchAllDriverManagers(nameForSearch, telephoneForSearch,
                    sexForSearch, 0, PAGE_MAX, (String)Session["CompanyName"]);
            }
            return View(lstModel);
        }

        private int GetDriverManagerAsNeeded(out IList<DriverManager> lstModel)
        {
            string name = Request.Form["Name"];
            string telephone = Request.Form["Telephone"];
            string sex = Request.Form["Sex"];
            string nameForSearch = "%%";
            string telephoneForSearch = "%%";
            string sexForSearch = "%%";
            ApplicantService applicantService = new ApplicantService();

            if (!string.IsNullOrEmpty(name) && name != "姓名")
                nameForSearch = string.Format("%{0}%", name);
            if (!string.IsNullOrEmpty(telephone) && telephone != "电话")
                telephoneForSearch = string.Format("%{0}%", telephone);
            if (!string.IsNullOrEmpty(sex) && sex != "性别")
                sexForSearch = string.Format("%{0}%", sex);
            DriverManagerService dms = new DriverManagerService();
            lstModel = dms.SearchAllDriverManagers(nameForSearch, telephoneForSearch, sexForSearch, (String)Session["CompanyName"]);

            int totalItems = lstModel.Count;

            if (!string.IsNullOrWhiteSpace(Request.Params["Page"]))
            {
                int page = int.Parse(Request.Params["Page"]);
                lstModel = dms.SearchAllDriverManagers(nameForSearch, telephoneForSearch,
                    sexForSearch, (page - 1) * PAGE_MAX, PAGE_MAX, (String)Session["CompanyName"]);
            }
            else
            {
                lstModel = dms.SearchAllDriverManagers(nameForSearch, telephoneForSearch,
                    sexForSearch, 0, PAGE_MAX, (String)Session["CompanyName"]);
            }

            return totalItems;
        }

        public ActionResult GetDriverManagerInfo(int id)
        {
            DriverManagerService dms = new DriverManagerService();
            IList<DriverManager> lstModel = dms.GetAllDriverManager();
            DriverManager driverManagerInfo = lstModel.Where(u => u.DriverManagerID == id).First();
            return View(driverManagerInfo);
        }

        //
        // GET: /DriverManager/Details/5

        public ViewResult Details(int id)
        {
            DriverManagerService dms = new DriverManagerService();
            IList<DriverManager> lstModel = dms.GetAllDriverManager();
            DriverManager driverManager = lstModel.Where(u => u.DriverManagerID == id).First();
            return View(driverManager);
        }

        //
        // GET: /DriverManager/Create

        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /DriverManager/Create

        [HttpPost]
        public ActionResult Create(DriverManager driverManager)
        {
            if (driverManager != null)
            {
                DriverManagerService dms = new DriverManagerService();
                driverManager.CompanyName = (String)Session["CompanyName"];
                Object thisLock = new Object();
                int id = 0;
                lock (thisLock)
                {
                    // Critical code section
                    dms.InsertDriverManager(driverManager);
                    id = (int)SqlMapperManager.Instance.Get().QueryForObject("SELECT_DRIVERMANAGER_IDENTITY", null);
                }
                HttpPostedFileBase file = Request.Files["file"];
                if (file.ContentLength > 0)
                {
                    string fileExt = Path.GetExtension(file.FileName).ToLower();
                    file.SaveAs(Server.MapPath("~/Photos/DriverManager") + @"\" + id + fileExt);
                    SqlMapperManager.Instance.Get().Update("UPDATE_DRIVERMANAGER_HEAD_IMAGE",
                        new
                        {
                            DriverManagerID = id,
                            Image = id + fileExt
                        });
                }
                return RedirectToAction("Index");
            }
            return View(driverManager);
        }


        //
        // GET: /DriverManager/Edit/5

        public ActionResult Edit(int id)
        {
            DriverManagerService dms = new DriverManagerService();
            IList<DriverManager> lstModel = dms.GetAllDriverManager();
            DriverManager driverManager = lstModel.Where(u => u.DriverManagerID == id).First();
            return View(driverManager);
        }

        //
        // POST: /DriverManager/Edit/5

        [HttpPost]
        public ActionResult Edit(DriverManager drivermanager)
        {
            if (ModelState.IsValid)
            {
                DriverManagerService dms = new DriverManagerService();
                dms.UpdateDriverManager(drivermanager);
                HttpPostedFileBase file = Request.Files["file"];
                if (file.ContentLength > 0)
                {
                    string fileExt = Path.GetExtension(file.FileName).ToLower();
                    file.SaveAs(Server.MapPath("~/Photos/DriverManager") + @"\" + drivermanager.DriverManagerID + fileExt);
                    SqlMapperManager.Instance.Get().Update("UPDATE_DRIVERMANAGER_HEAD_IMAGE",
                        new
                        {
                            DriverManagerID = drivermanager.DriverManagerID,
                            Image = drivermanager.DriverManagerID + fileExt
                        });
                }
                return RedirectToAction("Index");
            }
            else
            {
                return View(drivermanager);
            }
        }

        //
        // GET: /DriverManager/Delete/5

        public ActionResult Delete(int id)
        {
            DriverManagerService dms = new DriverManagerService();
            IList<DriverManager> lstModel = dms.GetAllDriverManager();
            DriverManager driverManager = lstModel.Where(u => u.DriverManagerID == id).First();
            return View(driverManager);
        }

        //
        // POST: /DriverManager/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            DriverManagerService dms = new DriverManagerService();
            int i = dms.DeleteDriverManager(id);
            if (i > 0)
            {
                return Json(new { Result = "true", Message = "删除成功" });
            }
            else
            {
                return Json(new { Result = "false", Message = "删除失败" });
            }
            //return RedirectToAction("Index");
        }

        [HttpPost, ActionName("UploadHeadImage")]
        public ActionResult UploadHeadImage()
        {
            HttpPostedFileBase file = Request.Files["file"];
            if (file.ContentLength > 0)
            {
                string fileExt = Path.GetExtension(file.FileName).ToLower();
                file.SaveAs(Server.MapPath("~/Photos/DriverManager") + @"\" + Request.Form["DriverManagerID"] + fileExt);
                try
                {
                    SqlMapperManager.Instance.Get().Update("UPDATE_DRIVERMANAGER_HEAD_IMAGE",
                        new
                        {
                            DriverManagerID = Request.Form["DriverManagerID"],
                            Image = Request.Form["DriverManagerID"] + fileExt
                        });
                    //return Json(new { Result = "true", Message = "头像更新成功" });
                    return Redirect("Edit/" + Request.Form["DriverManagerID"]);
                }
                catch (Exception ex)
                {
                    return Json(new { Result = "false", Message = ex.Message });
                }
            }
            else
            {
                return Json(new { Result = "false", Message = "头像更新失败" });
            }
        }

        //
        // POST: /DriverManager/GetPagingInfo

        [HttpGet, ActionName("GetPagingInfo")]
        public ActionResult GetPagingInfo()
        {
            int currentPage;
            if (string.IsNullOrWhiteSpace(Request.Params["Page"]))
                currentPage = 1;
            else
                currentPage = int.Parse(Request.Params["Page"]);
            IList<DriverManager> lstModel;
            string name = Request.Params["Name"];
            string telephone = Request.Params["Telephone"];
            string sex = Request.Params["Sex"];
            string nameForSearch = "%%";
            string telephoneForSearch = "%%";
            string sexForSearch = "%%";
            ApplicantService applicantService = new ApplicantService();

            if (!string.IsNullOrEmpty(name) && name != "姓名")
                nameForSearch = string.Format("%{0}%", name);
            if (!string.IsNullOrEmpty(telephone) && telephone != "电话")
                telephoneForSearch = string.Format("%{0}%", telephone);
            if (!string.IsNullOrEmpty(sex) && sex != "性别")
                sexForSearch = string.Format("%{0}%", sex);
            DriverManagerService dms = new DriverManagerService();
            lstModel = dms.SearchAllDriverManagers(nameForSearch, telephoneForSearch, sexForSearch, (String)Session["CompanyName"]);

            int itemCount = lstModel.Count;

            return Json(new
            {
                TotalItems = itemCount,
                ItemsPerPage = PAGE_MAX,
                CurrentPage = currentPage,
                TotalPages = (int)Math.Ceiling((decimal)itemCount / PAGE_MAX)
            }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult MyInformation()
        {
            if (Session["UserID"] == null)
                Response.Redirect("/Home/Login");
            int id = Convert.ToInt32(Session["UserID"]);
            DriverManagerService dms = new DriverManagerService();
            IList<DriverManager> lstModel = dms.GetAllDriverManager();
            DriverManager driverManagerInfo = lstModel.Where(u => u.DriverManagerID == id).First();
            return View(driverManagerInfo);
        }
    }
}